package com.hzhc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.entity.SysLog;
import com.hzhc.mapper.SysLogMapper;
import com.hzhc.service.SysLogService;
import com.hzhc.vo.SysLogVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 系统日志 服务实现类
 * </p>
 *
 * @author duanhm
 * @since 2019-08-02
 */
@Service
@RequiredArgsConstructor
public class SysLogServiceImpl extends ServiceImpl<SysLogMapper, SysLog> implements SysLogService {

	private final SysLogMapper sysLogMapper;

	@Override
	public List<SysLog> findLogsList(Page<SysLog> page, SysLogVo vo) {
		LambdaQueryWrapper<SysLog> queryWrapper = new LambdaQueryWrapper<SysLog>();
		if (StrUtil.isNotBlank(vo.getLoginName())) {
			queryWrapper.and(wrapper -> wrapper.like(SysLog::getLoginName, vo.getLoginName()).or().like(SysLog::getRealname,
					vo.getLoginName()));
		}
		if(StrUtil.isNotBlank(vo.getMenuName())){
			queryWrapper.like(SysLog::getMenuName,vo.getMenuName());
		}
		if(StrUtil.isNotBlank(vo.getAccesspath())){
			queryWrapper.eq(SysLog::getAccesspath,vo.getAccesspath());
		}
		if(StrUtil.isNotBlank(vo.getClientIp())){
			queryWrapper.like(SysLog::getClientIp,vo.getClientIp());
		}
		if(vo.getCreateTime()!=null){
			LocalDate localDate = vo.getCreateTime().toLocalDate();
			LocalDateTime stratTime = LocalDateTime.parse(localDate.toString() + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			LocalDateTime endTime = LocalDateTime.parse(localDate.toString() + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
			queryWrapper.ge(SysLog::getCreateTime, stratTime);
			queryWrapper.le(SysLog::getCreateTime, endTime);
		}
		queryWrapper.and(wrapper -> wrapper.isNotNull(SysLog::getClassName));
		queryWrapper.orderByDesc(SysLog::getCreateTime);

		IPage<SysLog> plist = page(page, queryWrapper);
		List<SysLog> list = plist.getRecords();

		return list;
	}

	@Override
	public Integer insert(SysLog sysLog) {
		return sysLogMapper.insert(sysLog);
	}
}
